package gmiddleware

import (
	"errors"
	"goweb/web/global"
	"goweb/web/model/common/request"
	"goweb/web/model/common/response"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/golang-jwt/jwt"
)

// Basic Auth 认证中间件
/**
使用 postman 测试时，认证选择Basic Auth，输入用户、密码即可
*/
func Auth() fiber.Handler {
	// 获取 auth 默认配置
	var authDefaultConfig = basicauth.ConfigDefault
	authDefaultConfig.Users = map[string]string{
		"john":  "doe",
		"admin": "123456",
	}
	authDefaultConfig.Realm = "Forbidden"
	authDefaultConfig.Authorizer = func(user, pass string) bool {
		if user == "john" && pass == "doe" {
			return true
		}
		if user == "admin" && pass == "123456" {
			return true
		}
		return false
	}

	// 登录失败则跳到 unauthorized.html页面
	authDefaultConfig.Unauthorized = func(c *fiber.Ctx) error {
		return c.SendFile("./unauthorized.html")
	}

	authDefaultConfig.ContextUsername = "_user"
	authDefaultConfig.ContextPassword = "_pass"
	return basicauth.New(authDefaultConfig)
}

// JWT auth
var (
	TokenExpired     = errors.New("Token is expired ")
	TokenNotValidYet = errors.New("Token not active yet ")
	TokenMalformed   = errors.New("That's not even a token ")
	TokenInvalid     = errors.New("Couldn't handle this token: ")
)

type JWT struct {
	SigningKey []byte
}

func NewJWT() *JWT {
	return &JWT{
		SigningKey: []byte(global.Config.Jwt.SigningKey),
	}
}

func JWTAuth() fiber.Handler {

	return func(c *fiber.Ctx) error {
		// 获取x-token请求头
		token := c.Get(global.Authorizer)
		if token == "" {
			return response.FailWithMessage("未登录或非法访问", c)
		}
		j := NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			return response.Result(global.ExpireToken, fiber.Map{"reload": true}, err.Error(), c)
		}
		// UUID 校验合法性
		c.Locals("claims", claims)
		return c.Next()
	}
}

// 解析token
func (j *JWT) ParseToken(tokenString string) (*request.TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &request.TokenClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*request.TokenClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid
	}
	return nil, TokenInvalid
}

// CreateToken 创建一个token
func (j *JWT) CreateToken(claims jwt.Claims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}
